/*	Copyright 2008 Jacquemin Valentin

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
	
	@author pollux
 */
package org.poxd.ui;

import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.InputStream;
import java.util.WeakHashMap;

import javax.imageio.ImageIO;
import javax.swing.Icon;
import javax.swing.ImageIcon;

import org.poxd.model.Content;

/**
 * @author pollux
 * 
 */
public class IconManager {
	private static IconManager instance;
	private WeakHashMap<Content, Icon> iconCash;

	private IconManager() {
		iconCash = new WeakHashMap<Content, Icon>();
	}

	/**
	 * Returns an instance of this singleton.
	 */
	public static IconManager getInstance() {
		if (instance == null) {
			instance = new IconManager();
		}
		return instance;
	}

	/**
	 * Returns an icon read from <code>content</code>
	 * 
	 * @param content
	 *            an objet containing an image
	 */
	public Icon getIcon(Content content) {
		Icon icon = createIcon(content);
		return icon;
	}

	/**
	 * Returns an icon created and scaled from the content of contentKey.
	 * 
	 * @param content
	 *            the content from which the icon image is read
	 * @param height
	 *            the desired height of the returned icon
	 * @param errorIcon
	 *            the returned icon in cas of error
	 */
	private Icon createIcon(Content content) {
		try {
			Icon ret = iconCash.get(content);
			if (ret == null) {
				// Read the icon of the piece
				InputStream contentStream = content.openStream();
				BufferedImage image = ImageIO.read(contentStream);
				contentStream.close();
				// TODO: manage min/max sizes
				ret = new ImageIcon(image);
				iconCash.put(content, ret);
			}
			return ret;

		} catch (IOException ex) {
			
		}
		return null;
	}
}
